﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SGRapidForm.Permission.Entity;
using SGRapidForm.Common;
using FishWebLib;
using System.Collections.Specialized;
using System.Web;
using System.Data;

namespace SGRapidForm.Permission.Component
{
    public class UserComponent : ComponentBase
    {
        /// <summary>
        /// 添加一位新用户
        /// </summary>
        /// <param name="UserDetails">一位用户</param>
        /// <returns>是否添加成功</returns>
        public bool AddUser(UserDetails userDetails)
        {
            return (FishBLLHelper.CallSpExecuteNonQuery("sgrf_permission_User_Add", userDetails) > 0);
        }

        /// <summary>
        /// 删除一位用户
        /// </summary>
        /// <param name="keyid">用户的Keyid</param>
        /// <returns>是否删除成功</returns>
        public bool DeleteUser(string keyid)
        {
            return (FishBLLHelper.CallSpExecuteNonQuery("sgrf_permission_User_Delete", null, keyid) > 0);
        }

        /// <summary>
        /// 批量删除用户
        /// </summary>
        /// <param name="keyids">keyids</param>
        /// <returns>批量删除是否成功</returns>
        public bool BulkDeleteUsers(string keyids)
        {
            //Keyid数量
            int count = SqlHelper.GetKeyidsCount(keyids);
            //Keyids转换成Sql语句
            keyids = SqlHelper.ConvertKeyidsToSqlStatement(keyids);

            return (FishBLLHelper.CallSpExecuteNonQuery("sgrf_permission_User_BulkDelete", null, keyids) == count);
        }

        /// <summary>
        /// 更新一位用户
        /// </summary>
        /// <param name="UserDetails">一位用户</param>
        /// <returns>是否更新成功</returns>
        public bool UpdateUser(UserDetails userDetails)
        {
            return (FishBLLHelper.CallSpExecuteNonQuery("sgrf_permission_User_Update", userDetails) > 0);
        }

        /// <summary>
        /// 更改用户密码
        /// </summary>
        public bool User_ChangePassword(string keyid, string password)
        {
            return (FishBLLHelper.CallSpExecuteNonQuery("[sgrf_permission_User_ChangePassword]", null, keyid, password) > 0);
        }

        /// <summary>
        /// 批量更新数据库
        /// </summary>
        /// <param name="columnSettings">列设置SQL</param>
        /// <param name="keyids">keyids集合</param>
        /// <returns>是否更新成功</returns>
        public bool BulkEditUsers(string columnSettings, string keyids)
        {
            NameValueCollection columnSettingsCollection = SqlHelper.ParseQueryString(columnSettings);
            StringBuilder sql = new StringBuilder();
            sql.Append(SqlHelper.GenerateSqlStatement(columnSettingsCollection, "Username", DbType.String, " Username = '{0}', "));
            sql.Append(SqlHelper.GenerateSqlStatement(columnSettingsCollection, "Email", DbType.String, " Email = '{0}', "));
            sql.Append(SqlHelper.GenerateSqlStatement(columnSettingsCollection, "MobilePhone", DbType.String, " MobilePhone = '{0}', "));
            sql.Append(SqlHelper.GenerateSqlStatement(columnSettingsCollection, "IsApproved", DbType.Boolean, " IsApproved = '{0}', "));
            sql.Append(SqlHelper.GenerateSqlStatement(columnSettingsCollection, "IsLockedOut", DbType.Boolean, " IsLockedOut = '{0}', "));
            sql.Append(SqlHelper.GenerateSqlStatement(columnSettingsCollection, "CreateDate", DbType.DateTime, " CreateDate = '{0}', "));

            //处理列设置语句
            columnSettings = SqlHelper.ProcessColumnSettings(sql.ToString());
            //Keyid数量
            int count = SqlHelper.GetKeyidsCount(keyids);
            //Keyids转换成Sql语句
            keyids = SqlHelper.ConvertKeyidsToSqlStatement(keyids);
            return false;
           // return (FishBLLHelper.CallSpExecuteNonQuery("sgrf_permission_User_BulkUpdate", null, columnSettings, keyids) == count);
        }

        /// <summary>
        /// 根据Keyid获取一位用户
        /// </summary>
        /// <param name="keyid">用户的Keyid</param>
        /// <returns>一位用户</returns>
        public UserDetails GetUserByKeyid(string keyid)
        {
            return FishBLLHelper.CallSpGetDataItem<UserDetails>("sgrf_permission_User_GetUserByKeyid", null, keyid);
        }

        /// <summary>
        /// 查询所有用户
        /// </summary>
        /// <returns>用户集合</returns>
        public List<UserDetails> GetAllUser()
        {
            return FishBLLHelper.CallSpGetDataItemList<UserDetails>("sgrf_permission_User_GetAll", null);
        }

        /// <summary>
        /// 根据条件得到所有用户信息
        /// </summary>
        /// <param name="filterConditions">条件值</param>
        /// <returns>返回集合</returns>
        public List<UserDetails> User_FilteredGetAll(string filterConditions)
        {
            NameValueCollection fieldCollection = SqlHelper.ParseQueryString(filterConditions);

            StringBuilder sql = new StringBuilder();
            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "RealName", DbType.String, " AND RealName like '%{0}%' "));;
            filterConditions = sql.ToString();
            return FishBLLHelper.CallSpGetDataItemList<UserDetails>("sgrf_permission_User_FilteredGetAll", null, filterConditions);
        }

        /// <summary>
        /// 进行过滤、排序、分页查询用户
        /// </summary>
        /// <param name="startRecord">开始记录索引</param>
        /// <param name="maxRecords">每页记录数</param>
        /// <param name="sortColumns">排序列</param>
        /// <param name="filterConditions">过滤条件SQL</param>
        /// <returns>用户集合</returns>
        public List<UserDetails> PagingGetUsers(Int32 startRecord, Int32 maxRecords, String sortColumns, String filterConditions)
        {
            VerifySortColumns(sortColumns);
            if (string.IsNullOrWhiteSpace(sortColumns))
            {
                sortColumns = "CreateDate ASC";
            }
           
            NameValueCollection fieldCollection = SqlHelper.ParseQueryString(filterConditions);

            StringBuilder sql = new StringBuilder();
       
            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "Username", DbType.String, " AND Username like '%{0}%' "));
            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "Realname", DbType.String, " AND Realname like '%{0}%' "));
            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "Email", DbType.String, " AND Email like '%{0}%' "));
            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "MobilePhone", DbType.String, " AND MobilePhone like '%{0}%' "));
            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "IsApproved", DbType.Boolean, " AND IsApproved = '{0}' "));
            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "IsLockedOut", DbType.Boolean, " AND IsLockedOut = '{0}' "));
            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "CreateDate", DbType.DateTime, " AND CONVERT(char(10), CreateDate,120) = '{0}' "));
            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "CreateName", DbType.String, " AND CreateName like '%{0}%' "));
            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "Age", DbType.String, " AND Age = '{0}' "));
            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "DeptName", DbType.String, " AND DeptName like '%{0}%' "));
            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "DeptCode", DbType.String, " AND DeptCode = '{0}' "));
            filterConditions = sql.ToString();

            return FishBLLHelper.CallSpGetDataItemList<UserDetails>("sgrf_permission_User_PagingGetUsers", null, startRecord, maxRecords, sortColumns, filterConditions);
        }

        /// <summary>
        /// 验证排序参数是否包含非法字符，有则抛出异常
        /// </summary>
        /// <param name="sortColumns"></param>
        private void VerifySortColumns(string sortColumns)
        {
            sortColumns = sortColumns.ToLowerInvariant().Replace(" asc", String.Empty).Replace(" desc", String.Empty);
            String[] columnNames = sortColumns.Split(',');

            foreach (String columnName in columnNames)
            {
                switch (columnName.Trim().ToLowerInvariant())
                {
                    case "username":
                    case "realname":
                    case "email":
                    case "mobilephone":
                    case "deptname":
                    case "isapproved":
                    case "islockedout":
                    case "createdate":
                    case "createname":
                    case "":
                        break;
                    default:
                        throw new ArgumentException("无效的排序列名");
                }
            }
        }

        /// <summary>
        /// 进行过滤、排序、分页查询用户记录数
        /// </summary>
        /// <param name="filterConditions">过滤条件</param>
        /// <returns>记录数</returns>
        public int PagingGetUsersCount (String filterConditions)
        {
            NameValueCollection fieldCollection = SqlHelper.ParseQueryString(filterConditions);

            StringBuilder sql = new StringBuilder();

            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "Username", DbType.String, " AND Username like '%{0}%' "));
            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "Realname", DbType.String, " AND Realname like '%{0}%' "));
            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "Email", DbType.String, " AND Email like '%{0}%' "));
            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "MobilePhone", DbType.String, " AND MobilePhone like '%{0}%' "));
            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "IsApproved", DbType.Boolean, " AND IsApproved = '{0}' "));
            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "IsLockedOut", DbType.Boolean, " AND IsLockedOut = '{0}' "));
            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "CreateDate", DbType.DateTime, " AND CONVERT(char(10), CreateDate,120) = '{0}' "));
            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "CreateName", DbType.String, " AND CreateName like '%{0}%' "));
            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "Age", DbType.String, " AND Age = '{0}' "));
            sql.Append(SqlHelper.GenerateSqlStatement(fieldCollection, "DeptName", DbType.String, " AND DeptName like '%{0}%' "));
            filterConditions = sql.ToString();

            return Convert.ToInt32(FishBLLHelper.CallSpExecuteScalar("sgrf_permission_User_PagingGetUsersCount", null, filterConditions));
        }

        /// <summary>
        /// 判断用户名是否存在
        /// </summary>
        /// <returns></returns>
        public bool IsExist(string userName) 
        {
            return ((int)FishBLLHelper.CallSpExecuteScalar("sgrf_permission_User_Exists", null, userName) == 1);
        }

        /// <summary>
        /// 根据UserName获取一位用户
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <returns>一位用户</returns>
        public UserDetails GetUserByName(string userName)
        {
            userName = SqlHelper.GenerateSqlParameter(userName,DbType.String);
            return FishBLLHelper.CallSpGetDataItem<UserDetails>("sgrf_permission_User_GetUserByName", null, userName);
        }

        #region 权限控制
        
        /// <summary>
        /// 用户是否拥有指定页面的权限
        /// </summary>
        /// <param name="userKeyid"></param>
        /// <param name="pageName"></param>
        /// <returns></returns>
        public bool HasPagePermission(string userKeyid, string pageCode)
        {
            return Convert.ToInt32(FishBLLHelper.CallSpExecuteScalar("sgrf_permission_User_HasPagePermission", null, userKeyid, pageCode)) > 0;
        }

        /// <summary>
        /// 用户是否拥有指定页面上的按钮权限
        /// </summary>
        /// <param name="userKeyid">用户keyid</param>
        /// <param name="pageCode">页面编码</param>
        /// <param name="methodName">方法名称</param>
        /// <returns></returns>
        public bool HasButtonPermission(string userKeyid, string pageCode, string serverSideMethod)
        {
            return Convert.ToInt32(FishBLLHelper.CallSpExecuteScalar("sgrf_permission_User_HasButtonPermission", null, userKeyid, pageCode, serverSideMethod)) > 0;
        }

       /// <summary>
       /// 获取用户拥有权限的模块
       /// </summary>
       /// <param name="userKeyid">用户Keyeid</param>
       /// <returns></returns>
        public List<ModuleEntity> GetModuleBy(string userKeyid)
        {
            return FishBLLHelper.CallSpGetDataItemList<ModuleEntity>("sgrf_permission_User_GetModuleBy", null, userKeyid);
        }

        /// <summary>
        /// 获取用户指定模块下拥有权限的一级页面
        /// </summary>
        /// <param name="userKeyid">用户Keyeid</param>
        /// <param name="moduleKeyid">模块Keyeid</param>
        /// <returns></returns>
        public List<PageEntity> GetPageBy(string userKeyid, string moduleKeyid)
        {
            return FishBLLHelper.CallSpGetDataItemList<PageEntity>("sgrf_permission_User_GetPageBy", null, userKeyid, moduleKeyid);
        }

        /// <summary>
        /// 获取用户指定模块下拥有权限的二级页面
        /// </summary>
        /// <param name="userKeyid">用户Keyeid</param>
        /// <param name="moduleKeyid">模块Keyeid</param>
        /// <returns></returns>
        public List<PageEntity> GetSecondStagePageBy(string userKeyid, string moduleKeyid)
        {
            return FishBLLHelper.CallSpGetDataItemList<PageEntity>("sgrf_permission_User_GetSecondStagePageBy", null, userKeyid, moduleKeyid);
        }

        /// <summary>
        /// 获取用户指定页面下拥有权限的安妮
        /// </summary>
        /// <param name="userKeyid">用户Keyeid</param>
        /// <param name="pageName">页面代码</param>
        /// <returns></returns>
        public List<ButtonEntity> GetButtonBy(string userKeyid, string pageCode)
        {
            return FishBLLHelper.CallSpGetDataItemList<ButtonEntity>("sgrf_permission_User_GetButtonBy", null, userKeyid, pageCode);
        }

        #endregion

        /// <summary>
        /// 导入用户数据
        /// </summary>
        public bool User_ImportDate(string userName, string password, string realName, string mobilePhone, string email, bool isApproved, bool isLockedOut, string remark, string createName, DateTime createDate, string deptName, string roleName)
        {
            return (FishBLLHelper.CallSpExecuteNonQuery("sgrf_permission_User_ImportDate", null, userName, password, realName, mobilePhone, email, isApproved, isLockedOut, remark, createName, createDate, deptName, roleName) > 0);
        }

        /// <summary>
        /// 清空用户数据
        /// </summary>
        /// <returns></returns>
        public bool User_Clear()
        {
            FishBLLHelper.CallSpExecuteNonQuery("sgrf_permission_User_Clear", null);
            return true;
        }

       /// <summary>
        /// 根据岗位名称、页面编码、按钮编码的权限来获得用户
        /// </summary>
        /// <param name="filterConditions">条件值</param>
        /// <returns>返回集合</returns>
        public List<UserDetails> User_GetUserByButtonPermission(string pagecode,string buttoncode)
        {

            return FishBLLHelper.CallSpGetDataItemList<UserDetails>("sgrf_permission_User_GetUserByButtonPermission", null, pagecode,buttoncode);
        }

               /// <summary>
        /// 根据岗位名称、页面编码、按钮编码的权限来获得用户
        /// </summary>
        /// <param name="filterConditions">条件值</param>
        /// <returns>返回集合</returns>
        public List<UserDetails> User_GetUserByDeptCode(string deptcode)
        {

            return FishBLLHelper.CallSpGetDataItemList<UserDetails>("sgrf_permission_User_GetUserByDeptCode", null, deptcode);
        }
        
            

    }
}
